package com.joelaws.prototype.server.blackberry;

import java.util.List;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import com.joelaws.prototype.client.data.User;
import com.joelaws.prototype.client.util.Create;
import com.joelaws.prototype.server.DatingImpl;

public class UserMeetingList extends Resource {

	private long userID;

	public UserMeetingList(Context context, Request request, Response response) {
		super(context, request, response);

		String[] data = request.getResourceRef().getRemainingPart().split("=");
		if (data != null && data.length == 2)
			userID = Long.parseLong(data[1]);
		else
			userID = Long.MIN_VALUE;

		super.getVariants().add(new Variant(MediaType.TEXT_PLAIN));
	}

	@Override
	public Representation getRepresentation(Variant variant) {
		if (userID == Long.MIN_VALUE)
			return new StringRepresentation("Invalid userID",
					MediaType.TEXT_PLAIN);

		List<User> users;
		try {
			users = new DatingImpl().getMeetingUsers(userID);
		} catch (Exception e) {
			e.printStackTrace();
			users = Create.newList();
		}

		StringBuilder builder = new StringBuilder("");
		int count = 0;
		for (User user : users) {
			builder.append(user.getUserID());
			count++;
			if (count < users.size()) {
				builder.append(":");
			}
		}

		String result = builder.toString();
		if (result == null || result.length() == 0) {
			result = "none";
		}
		return new StringRepresentation(result, MediaType.TEXT_PLAIN);
	}

	public static String getURL() {
		return "/getUserMeetingList";
	}
}
